package aggregation

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/errcode"
	pb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/aggregation"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/aggregation/statistics"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
)

type StatisticsServer struct {
	statisticsService statistics.StatisticsServiceIface
}

func NewStatisticsServer(statisticsService statistics.StatisticsServiceIface) pb.StatisticsServiceServer {
	return &StatisticsServer{
		statisticsService: statisticsService,
	}
}

func (s *StatisticsServer) StatisticsData(ctx context.Context, request *pb.StatisticsDataRequest) (*pb.StatisticsDataResponse, error) {
	response, err := s.statisticsService.StatisticsData(ctx, request)
	if err != nil {
		stark.Logger.Infof(ctx, "StatisticsData-error: %+v", err)
		return response, errcode.CTogRPCError(err)
	}
	return response, nil
}

func (s *StatisticsServer) UseRankList(ctx context.Context, request *pb.UseRankListRequest) (*pb.UseRankListResponse, error) {
	response := &pb.UseRankListResponse{}

	if request.Type == 0 {
		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "Type不能为空")
	}
	if request.Type < 0 || request.Type > 3 {
		return response, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "Type参数错误")
	}

	list, err := s.statisticsService.UseRankList(ctx, request)
	if err != nil {
		stark.Logger.Infof(ctx, "StatisticsList-error: %+v", err)
		return response, errcode.CTogRPCError(err)
	}

	for _, item := range list {
		beCopyItem := &pb.UseRankItem{
			Total:    item.Total,
			UserId:   item.UserId,
			UserName: item.UserName,
		}
		response.List = append(response.List, beCopyItem)
	}

	return response, nil
}
